// pages/teacher/index.js
const app = getApp()
var sliderWidth = 96;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    current: 2,
    pages: 0,
    activeIndex: 0,
    sliderOffset: 0,
    tabs: ["排课", "未开课程", "已开课程"],
    unStartCourseList: null,
    startedCourseList: null,
    user: null,
    house: null,
    courseList: null,
    roomList: null,
    date: "",
    startTime: "",
    endTime: "",
    selectedCourse: null,
    selectedRoom: null,
    actionSheetHidden: true,
    reserveList: null,
    createOrEdit: null,
    selectReserve: null,
    actionSheetHidden4ReserveDetail: true,
    reserveDetailList: null,
    selectedReserveId: null,
    teacherList: null,
    selectedTeacher: null,
    customerList: null,
    selectedCustomer: null
  },

  showReserveDetail2(e) {
    console.log(e);
    let that = this;
    wx.navigateTo({
      url: "./reserveDetail/index?obj=" + JSON.stringify(e.currentTarget.dataset.obj)
    });

  },

  deleteReserve(e) {
    console.log(e);
    let that = this;

    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用删除方法了
          wx.request({
            url: app.globalData.serverUrl + "/reserve/deleteReserve",
            header: {
              token: app.globalData.token
            },
            data: {
              reserveDetailId: e.currentTarget.dataset.obj.id
            },
            success(resp) {
              console.log(resp);
      
              if (resp.data.success) {
                that.getReserveDetailList(e.currentTarget.dataset.obj.reserveId);
              }
            },
            fail(resp) {
              console.error(resp);
            }
          });

        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    });
  },

  goHome() {
    wx.switchTab({
      url: '../homePage/index'
    });
  },

  editSchedule(e) {
    var that = this;
    var item = e.currentTarget.dataset.item; //获取当前长按图片下标

    this.data.customerList.forEach(function (element) {
      if (element.id == item.customerId) {
        that.setData({
          selectedCustomer: element
        });
      }
    });

    this.data.courseList.forEach(function(element) {
      if(element.id == item.courseId) {
        that.setData({
          selectedCourse: element
        });
      }
    });

    this.data.roomList.forEach(function(element) {
      if(element.id == item.classRoomId) {
        that.setData({
          selectedRoom: element
        });
      }
    });

    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden,
      createOrEdit: '编辑',
      date: item.courseStartTime.split(" ")[0],
      startTime: item.courseStartTime.split(" ")[1],
      endTime: item.courseStartTime.split(" ")[1],
      selectReserve: item
    });
  },

  deleteSchedule(e) {
    var that = this;
    var item = e.currentTarget.dataset.item; //获取当前长按图片下标

    wx.showModal({
      title: '提示',
      content: '确认删除吗？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.serverUrl + "/reserve/deleteSchedule",
            header: {
              token: app.globalData.token
            },
            data: {
              id: item.id
            },
            success(resp) {
              console.log(resp);
              if (resp.data.success) {
                that.getReserveList();
              }
            },
            fail(resp) {
              console.error(resp);
            }
          });

        } else if (res.cancel) {
          console.log('点击取消了');
        }
      }
    });
  },

  // 某个私教老师的排课情况
  getReserveList() {
    let that = this;

    wx.request({
      url: app.globalData.serverUrl + "/reserve/queryScheduleList",
      header: {
        token: app.globalData.token
      },
      success(resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            reserveList: resp.data.data
          });
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });
  },

  showActionSheet() {
    this.setData({
      createOrEdit: '新建',
      actionSheetHidden: !this.data.actionSheetHidden,
      selectedCourse: null,
      selectedRoom: null,
      date: "",
      startTime: "",
      endTime: "",
      selectedCustomer: null,
      selectReserve: null
    });
  },

  showActionSheet4ReserveDetail() {
    this.setData({
      actionSheetHidden4ReserveDetail: !this.data.actionSheetHidden4ReserveDetail,
    });
  },

  listenerActionSheet: function (e) {
    console.log(e);

    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    });
  },

  listenerActionSheet4ReserveDetail: function (e) {
    console.log(e);

    this.setData({
      actionSheetHidden4ReserveDetail: !this.data.actionSheetHidden4ReserveDetail
    });
  },

  createReserve(e) {
    console.log(e);
    let that = this;

    if(this.data.selectedCustomer == null) {
      wx.showToast({
        title: '请选择客户',
        icon: 'none',
        duration: 2000
      });

      return;
    }

    if(this.data.selectedCourse == null) {
      wx.showToast({
        title: '请选择课程',
        icon: 'none',
        duration: 2000
      });

      return;
    }

    if(this.data.selectedRoom == null) {
      wx.showToast({
        title: '请选择教室',
        icon: 'none',
        duration: 2000
      });

      return;
    }

    if(this.data.date == null || this.data.date == "") {
      wx.showToast({
        title: '请选择日期',
        icon: 'none',
        duration: 2000
      });

      return;
    }

    if(this.data.startTime == null || this.data.startTime == "") {
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none',
        duration: 2000
      });

      return;
    }

    if(this.data.endTime == null || this.data.endTime == "") {
      wx.showToast({
        title: '请选择结束时间',
        icon: 'none',
        duration: 2000
      });

      return;
    }

    let obj = {
      customerId: this.data.selectedCustomer.id,
      courseId: this.data.selectedCourse.id,
      classRoomId: this.data.selectedRoom.id,
      courseStartTime: this.data.date + " " + this.data.startTime,
      courseEndTime: this.data.date + " " +  this.data.endTime,
      status: 1
    }

    if(this.data.selectReserve != null)
      obj.id = this.data.selectReserve.id;

    wx.request({
      url: app.globalData.serverUrl + '/reserve/createOrEditSchedule4Sij',
      method: "POST",
      header: {
        token: app.globalData.token
      },
      data: obj,
      success: function (resp) {
        wx.hideLoading();
        console.log(resp);
        if (resp.data.success) {
          wx.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000
          });

          that.getReserveList();

        } else {
          wx.showToast({
            title: resp.data.errorMsg,
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: function (error) {
        wx.hideLoading();
        console.error(error);
      }
    });
  },

  bindPickerChange: function (e) {
    console.log(e)

    if (e.target.id == "customer") {
      this.setData({
        selectedCustomer: this.data.customerList[e.detail.value]
      });
    }

    if (e.target.id == "a") {
      this.setData({
        selectedCourse: this.data.courseList[e.detail.value]
      });
    }

    if (e.target.id == "b") {
      this.setData({
        selectedRoom: this.data.roomList[e.detail.value]
      });
    }
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  bindTimeChange: function (e) {
    if (e.target.id == "c") {
      this.setData({
        startTime: e.detail.value
      })
    }

    if (e.target.id == "d") {
      this.setData({
        endTime: e.detail.value
      })
    }
  },

  getReserveDetailList(_reserveId) {
    console.log(_reserveId);
    let that = this;

    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    wx.request({
      url: app.globalData.serverUrl + '/reserve/queryReserveDetailList',
      header: {
        token: app.globalData.token
      },
      data: {
        reserveId: _reserveId,
      },
      success: function (resp) {
        wx.hideLoading();
        console.log(resp);

        if (resp.data.success) {
          that.setData({
            reserveDetailList: resp.data.data
          });
        }
      },
      fail: function (error) {
        wx.hideLoading();
        console.error(error);
      }
    });
  },


  showReserveDetail(e) {
    console.log(e);
    let that = this;

    this.setData({
      selectedReserveId: e.currentTarget.dataset.id
    });

    this.getReserveDetailList(e.currentTarget.dataset.id);
    this.showActionSheet4ReserveDetail();   
  },

  updateCourseTeacher(reserveId) {
    wx.request({
      url: app.globalData.serverUrl + '/reserve/updateCourseTeacherById',
      header: {
        token: app.globalData.token
      },
      data: {
        id: reserveId
      },
      success: function (resp) {
        wx.hideLoading();
        console.log(resp);
        if (resp.data.success) {
          wx.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: function (error) {
        wx.hideLoading();
        console.error(error);
      }
    });
  },

  startCourse(e) {
    console.log(e);
    let that = this;

    wx.showModal({
      title: '提示',
      content: '确定开课吗？',
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用删除方法了
          wx.request({
            url: app.globalData.serverUrl + '/reserve/startCourse',
            header: {
              token: app.globalData.token
            },
            data: {
              reserveId: that.data.selectedReserveId
            },
            success: function (resp) {
              wx.hideLoading();
              console.log(resp);
              if (resp.data.success) {
                that.updateCourseTeacher(that.data.selectedReserveId);
                wx.showToast({
                  title: '操作成功',
                  icon: 'none',
                  duration: 2000
                });
                
                that.unStartCourseList();

              }
            },
            fail: function (error) {
              wx.hideLoading();
              console.error(error);
            }
          });

        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    });
  },

  tabClick: function (e) {
    console.log(e);
    let that = this;
    let currentTarget = 0;

    // 我的排课列表
    if (e.currentTarget.id == 0) {
      this.getReserveList();
    }

    // 未开课列表
    if (e.currentTarget.id == 1) {
      currentTarget = 1;
      this.unStartCourseList();
    }

    // 已开课列表
    if (e.currentTarget.id == 2) {
      currentTarget = 2;
      this.startedCourseList();
    }

    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id,
      current: 2,
      currentTarget: currentTarget
    });
  },

  unStartCourseList(e) {
    let that = this;

    wx.request({
      url: app.globalData.serverUrl + '/reserve/getUnStartCourseList',
      header: {
        token: app.globalData.token
      },
      data: {
        current: 1
      },
      success: function (resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            pages: resp.data.data.pages,
            unStartCourseList: resp.data.data.records,
          });
        }
      },
      fail: function (error) {
        console.error(error);
      }
    });
  },

  startedCourseList(e) {
    let that = this;
    
    wx.request({
      url: app.globalData.serverUrl + '/reserve/getStartedCourseList',
      header: {
        token: app.globalData.token
      },
      data: {
        current: 1
      },
      success: function (resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            pages: resp.data.data.pages,
            startedCourseList: resp.data.data.records,
          });
        }
      },
      fail: function (error) {
        console.error(error);
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

    that.setData({
      createOrEdit: '新建'
    });

    this.setData({
      user: app.globalData.sysUser
    });
    
    // app.globalData.token = 'eyJhbGciOiJIUzI1NiJ9.eyJzeXNVc2VyIjoie1wiYXZhdGFyVXJsXCI6XCJodHRwczovL3d4LnFsb2dvLmNuL21tb3Blbi92aV8zMi9RMGo0VHdHVGZUTE0wSjk0NzcxNEpidHpPTDRLd2dpYkhRU0piSEpNNHhLd0hqVkZQWHZFcUFGUlFVb1JEaWFiOFA5TWQwUDZhNzNyY1E3UExpY3pXY0k1US8xMzJcIixcImNpdHlcIjpcIkRheGluZ1wiLFwiY3JlYXRlVGltZVwiOlwiMTU2MjY4NTUyNjAwMFwiLFwiZW50ZXJwcmlzZUlkXCI6MSxcImdlbmRlclwiOlwiMVwiLFwiaWRcIjoxMDUsXCJpbnRyb1wiOlwiXCIsXCJtb2JpbGVcIjpcIjE1NTM5MjAwNjI5XCIsXCJuaWNrTmFtZVwiOlwi5oiR5piv6ICB5YiYXCIsXCJwcm92aW5jZVwiOlwiQmVpamluZ1wiLFwicmVhbE5hbWVcIjpcIuaZqOaZqFwiLFwicm9sZUlkXCI6Mn0ifQ.DHnS7YgKzslwLRIAMvEQF3ae-Pi8ARkGuYubnNRlWO8';

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });

    // 查询这个企业下的所有教室
    wx.request({
      url: app.globalData.serverUrl + '/classroom/queryClassRoomList',
      header: {
        token: app.globalData.token
      },
      success: function (resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            roomList: resp.data.data,
          });
        }
      },
      fail: function (error) {
        console.error(error);
      }
    });

    // 查询这个企业下的所有课程
    wx.request({
      url: app.globalData.serverUrl + '/course/queryCourseListByType',
      header: {
        token: app.globalData.token
      },
      data: {
        type: "courseType_3"
      },
      success: function (resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            courseList: resp.data.data,
          });
        }
      },
      fail: function (error) {
        console.error(error);
      }
    });

    // 私教排班列表
    this.getReserveList();

    // // 教师列表
    // wx.request({
    //   url: app.globalData.serverUrl + '/user/queryTeacherList',
    //   header: {
    //     token: app.globalData.token
    //   },
    //   success: function (resp) {
    //     console.log(resp);
    //     if (resp.data.success) {
    //       if (resp.data.data.length > 0) {
    //         resp.data.data[0].selected = true;
    //         that.setData({
    //           teacherList: resp.data.data,
    //         });
    //       }
    //     }
    //   }
    // });

    // 客户列表
    wx.request({
      url: app.globalData.serverUrl + '/user/queryUserListByRole',
      header: {
        token: app.globalData.token
      },
      data: {
        roleId: 1
      },
      success: function (resp) {
        console.log(resp);
        if (resp.data.success) {
          if (resp.data.data != null) {
            let tmp = [];
            resp.data.data.forEach(element => {
              if(element.realName != null)
                tmp.push(element);
            });
            that.setData({
              customerList: tmp
            });
          }
        }
      }
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;

    if (that.data.current <= that.data.pages) {
      if (that.data.currentTarget == 1) {
        wx.request({
          url: app.globalData.serverUrl + '/reserve/getUnStartCourseList',
          header: {
            token: app.globalData.token
          },
          data: {
            current: that.data.current
          },
          success: function (resp) {
            console.log(resp);
            if (resp.data.success) {
              let newCurrent = that.data.current + 1;

              let tmp = that.data.unStartCourseList;
              resp.data.data.records.forEach(element => {
                tmp.push(element);
              });

              that.setData({
                current: newCurrent,
                unStartCourseList: tmp,
              });
            }
          },
          fail: function (error) {
            console.error(error);
          }
        });
      }

      if (that.data.currentTarget == 2) {
        wx.request({
          url: app.globalData.serverUrl + '/reserve/getStartedCourseList',
          header: {
            token: app.globalData.token
          },
          data: {
            current: that.data.current
          },
          success: function (resp) {
            console.log(resp);
            if (resp.data.success) {
              let newCurrent = that.data.current + 1;

              let tmp = that.data.startedCourseList;
              resp.data.data.records.forEach(element => {
                tmp.push(element);
              });

              that.setData({
                current: newCurrent,
                startedCourseList: tmp,
              });
            }
          },
          fail: function (error) {
            console.error(error);
          }
        });
      }

    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})